package io.github.iogogogo.commons.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tao.zeng on 2024/11/7.
 * <p>
 * 驼峰命名和下划线命名互转
 * <p>
 * com.google.common.base.CaseFormat
 * <p>
 * <a href="https://www.yiibai.com/guava/guava_caseformat.html">Guava CaseFormat类</a>
 * <p>
 *
 * @see SuperStringUtils#humpToLine(String)
 * @see SuperStringUtils#lineToHump(String)
 */
@Deprecated
public class CasesUtils {

    private static final Pattern CAMELCASE_PATTERN = Pattern.compile("[A-Z]");
    private static final Pattern UNDERLINE_PATTERN = Pattern.compile("_[a-z]");
    private static final char UNDERLINE = '_';

    /**
     * 驼峰命名（形如：UserInfo）转化为下划线命名（user_info）
     *
     * @param camelCase 驼峰格式的字符串
     * @return 下划线形式的字符串
     */
    public static String camelCase2UnderlineCase(String camelCase) {
        Matcher matcher = CAMELCASE_PATTERN.matcher(camelCase);
        StringBuilder builder = new StringBuilder(camelCase);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() + i, matcher.end() + i, UNDERLINE + matcher.group().toLowerCase());
        }
        if (builder.charAt(0) == UNDERLINE) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    /**
     * 下划线命名（user_info）转化为驼峰命名（形如：userInfo）
     *
     * @param underlineCase 下划线形式的字符串
     * @return 驼峰格式的字符串
     */
    public static String underlineCase2CamelCase(String underlineCase) {
        Matcher matcher = UNDERLINE_PATTERN.matcher(underlineCase);
        StringBuilder builder = new StringBuilder(underlineCase);
        for (int i = 0; matcher.find(); i++) {
            builder.replace(matcher.start() - i, matcher.end() - i, matcher.group().substring(1).toUpperCase());
        }
        if (Character.isUpperCase(builder.charAt(0))) {
            builder.replace(0, 1, String.valueOf(Character.toLowerCase(builder.charAt(0))));
        }
        return builder.toString();
    }
}
